package com.example.wisdomclassroomapi.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

/**
 * 图形验证码工具类
 */
@Slf4j
public class ImageVerificationCodeUtil {
    private final String[] SEEDS = {"0","1","2","3","4","5","6","7","8","9",
            "a","b","c","d","e","f","g","h","i","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z"};

    /**
     * 获取随机码字符串
     *
     * @param size 随机码字符串位数
     * @return String 随机码字符串
     */
    public String getRandomCode(int size) {
        Random random = new Random(System.currentTimeMillis());
        StringBuilder stringBuilder = new StringBuilder(size);
        int number = SEEDS.length;
        for(int i = 0; i < size; i++) {
            stringBuilder.append(SEEDS[random.nextInt(number)]);
        }
        return stringBuilder.toString();
    }

    /**
     * 获取图形验证码（返回Base64编码）
     *
     * @param randomCode 验证码
     * @return String Base64编码格式的图形验证码
     */
    public String getImageCode(String randomCode) {
        // 生成随机类
        Random random = new Random(System.currentTimeMillis());

        // 在内存中创建图象
        int imageWidth = 68;
        int imageHeight = 68;
        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics graphics = image.getGraphics();
        // 设定背景色
        graphics.fillRect(0, 0, imageWidth, imageHeight);
        // 设定字体
        String fontName = "Times New Roman";
        graphics.setFont(new Font(fontName, Font.PLAIN, 24));
        // 随机产生160条干扰线，使图象中的认证码不易被其它程序探测到
        graphics.setColor(getRandColor(160, 200));
        for (int i = 0; i < 160; i++) {
            int x = random.nextInt(imageWidth);
            int y = random.nextInt(imageHeight);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            graphics.drawLine(x, y, x + xl, y + yl);
        }

        // 将认证码显示到图象中
        for (int i = 0; i < randomCode.length(); i++) {
            // 设置颜色
            graphics.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            // 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
            graphics.drawString(randomCode.substring(i, i + 1), 13 * i + 8, 26);
        }

        // 图象生效
        String result = null;
        graphics.dispose();
        try (ByteArrayOutputStream output = new ByteArrayOutputStream();
             ImageOutputStream imageOut = ImageIO.createImageOutputStream(output)) {
            ImageIO.write(image, "JPEG", imageOut);
            result = Base64.getEncoder().encodeToString(output.toByteArray());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return result;
    }

    /**
     * 给定范围获得随机颜色
     */
    private Color getRandColor(int fc, int bc) {
        Random random = new Random(System.currentTimeMillis());
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}
